<?php
namespace Home\Model;
use Think\Model;

class callBackModel extends Model{
	public function __construct() {
		parent::__construct();
	}
	
	//验证签名
	public function valid($_token)
	{		
		$echoStr = $_GET["echostr"];
		$signature = $_GET["signature"];
		$timestamp = $_GET["timestamp"];
		$nonce = $_GET["nonce"];
		$token = $_token;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode($tmpArr);
		$tmpStr = sha1($tmpStr);
		if($tmpStr == $signature){
			echo $echoStr;
			exit;
		}
	}
	
	//响应消息
	public function responseMsg()
	{
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		if (!empty($postStr)){
			$this->logger("R \r\n".$postStr);
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$RX_TYPE = trim($postObj->MsgType);
			
			//消息类型分离
			switch ($RX_TYPE)
			{
				case "event":
					$result = $this->receiveEvent($postObj);
					break;
				case "text":
					$result = $this->receiveText($postObj);
					break;
				case "image":
					$result = $this->receiveImage($postObj);
					break;
				case "location":
					$result = $this->receiveLocation($postObj);
					break;
				case "voice":
					$result = $this->receiveVoice($postObj);
					break;
				case "video":
				case "shortvideo":
					$result = $this->receiveVideo($postObj);
					break;
				case "link":
					$result = $this->receiveLink($postObj);
					break;
				default:
					$result = "unknown msg type: ".$RX_TYPE;
					break;
			}
			$this->logger("T \r\n".$result);
			echo $result;
		}else {
			echo "";
			exit;
		}
	}
	
	//接收事件消息
	private function receiveEvent($object)
	{
		//获取最新历史记录
		$history = D("read_history")->where("open_id='".$object->FromUserName."'")->order("addtime desc")->find();
		//获取用户所绑定的域名
		$user = D("user")->where("open_id='".$object->FromUserName."'")->find();
		$info = "";
		if(!empty($history)) {
			//获取最新历史的下一章节地址
			$next_chapter = D("novel_chapter")->where("novel_id=".$history["novel_id"]." and id > ".$history["chapter_id"])->find();
			$info = "欢迎关注「最全书城」, 您上次看到了《".$history["novel_name"]."》".$history["chapter"]."。 \n\n\n<a href='http://".$user["domain"]."/Home/Novel/show/id/".$next_chapter["id"]."/novel_id/".$next_chapter["novel_id"]."'>【点此继续阅读】</a>\n\n\n为方便下次阅读，请置顶公众号";
		}
		else{
			$info = "欢迎关注「最全书城」, 您上次看到了《拿手,我下针》第三章 \n\n\n<a href='http://elumvy.cn/Home/Novel/show/id/565792/novel_id/900'>【点此继续阅读..】</a>\n\n\n为方便下次阅读，请置顶公众号";
		}
			
		$content = "";
		switch ($object->Event)
		{
			case "subscribe": 
				$content = $info;
				//如果关注就修改用户信息为关注
				$data["subscribe"] = 1;
				D("user")->where("open_id='".$object->FromUserName."'")->save($data);

				$open_id = $object->FromUserName;
				//查出活动被推出人信息
				$proxys = D("user")->where("open_id = '$open_id'")->find();
				$proxy_openid = $proxys['proxy_open_id'];
				//查出活动推出时间
				$time = date('Y-m-d',time());	
				$send_arr = D('activity')->where("type=2 and status=1 and start_time <= '$time' and end_time>='$time'")->find();
				//查出推广人的时间
				$proxy_arr = D('user')->where("open_id='$proxy_openid'")->find();
				if(!empty($proxys['proxy_open_id']) && !empty($send_arr) && empty($proxys['first_subscribe_time'])){
					$subscribe_money = $send_arr['subscribe_money'];
					//活动推出人的书币查询
					$proxy_book_money = $proxy_arr['book_money'];
					$map['book_money'] = $proxy_book_money+$subscribe_money;
					$map_new['first_subscribe_time'] = time();
					//存入被推广人关注时间
					D('user')->where("open_id='$open_id'")->save($map_new);
					//存入推广人书币
					D('user')->where("open_id = '$proxy_openid'")->save($map);
					//推送一条模板消息
					$old_nickname = $proxy_arr['nickname'];
					$new_nickname = $proxys['nickname'];
					$domain = $proxy_arr['domain'];
					
					$this->sendtemplateinfo($domain,'@'.$old_nickname.'       您推荐的好友'.$new_nickname.'已关注了本平台',$old_nickname,$subscribe_money,$proxy_openid);
					
					
				}
				break;			
			case "unsubscribe":
				//如果关注就修改用户信息为不关注
				$data["subscribe"] = 0;
				D("user")->where("open_id='".$object->FromUserName."'")->save($data);			
				$content = "取消关注";
				break;
			case "CLICK":
                $content = '亲，请问您有什么需要帮助的吗？';
				break;
			default:
				$content = "receive a new event: ".$object->Event;
				break;
		}
		
		if(is_array($content)){
			$result = $this->transmitNews($object, $content);
		}else{
			$result = $this->transmitText($object, $content);
		}
		return $result;
	}
	
	//接受文字消息
	private function receiveText($object)
	{
		$keyword = trim($object->Content);
		if($keyword == "1" )
		{
			
			$content = "免费参与方法：\n<a href=\"http://h.xkrq.net.cn\">点击这里,发送到【三个群】</a>\n并加上一句【我已报名，免费摄影速成班，有没有小伙伴一起的？】\n(群人数不少于50人)发表后请截图发回本微信，完成后，请回复数字: 2";
			
		}
		
		if($keyword == "2" )
		{
			
			$content = "【还差最后一步】\n<a href=\"http://h.yprs.net.cn\">点击这里，分享到朋友圈</a>\n并加上一句【我已报名，免费摄影速成班，有没有小伙伴一起的？】发表后请截图发回本微信，完成后，请回复数字 3";
			
		}
		
		
		if($keyword == "3" )
		{
			
			$content = "恭喜您，感谢您的参与，因参与人数较多！请耐心等候！\n<a href=\"http://h.krmc.net.cn\">点击添加客服</a>\n同时注意【删除盆友圈无效，您的微信名称头像请务必不要修改，严格根据头像和名称双重验证】\n未完成任务,请先完成后截图过来，否则审核无效！";
			
		}
		
		if($keyword == "欲望"){
			$dataAll[0] = [
				'title' => "老公和小三开房5小时，监控视频让老婆看后崩溃！",
				'description' => "",
				'url' => "http://qikaism.cn/Home/Novel/show/id/76582/novel_id/136",
				'picurl' => "http://bedrum.cn/Public/attached/2017/09/01/novel2017090159a93619c932a.png",
			];	
			$dataAll[1] = [
				'title' => "和美女相遇，那一夜居然要我给她.",
				'description' => "",
				'url' => "http://qikaism.cn/Home/Novel/show/id/557384/novel_id/890",
				'picurl' => "http://bedrum.cn/Public/attached/2017/09/01/novel2017090159a93650c90fa.png",
			];
			$dataAll[2] = [
				'title' => "农村妇女为什么要偷人，总是喜欢半推半就..",
				'description' => "",
				'url' => "http://qikaism.cn/Home/Novel/show/id/559686/novel_id/892",
				'picurl' => "http://bedrum.cn/Public/attached/2017/09/01/novel2017090159a9391812900.png",
			];
			$dataAll[3] = [
				'title' => "睡老婆和睡情人，在男人的眼里最大的区别竟然是这个......",
				'description' => "",
				'url' => "http://qikaism.cn/Home/Novel/show/id/560197/novel_id/893",
				'picurl' => "http://bedrum.cn/Public/attached/2017/09/01/novel2017090159a938f9053aa.png",
			];
			$dataAll[4] = [
				'title' => "搜索更多",
				'description' => "",
				'url' => "http://qikaism.cn/Home/Novel/search",
				'picurl' => "",
			];			
			
			$jsondata = json_encode($dataAll,JSON_UNESCAPED_UNICODE);
			$datanews = '{
				"articles": '.$jsondata.'
			}';
			$map['domain'] = "qikaism.cn";
			$platform = D("platform")->where($map)-> find();
			if(intval($platform["out_time"]) > time())	{
				$token = getWeChatToken($platform["appid"],$platform["secret"],$platform["token"]);
			}else{
				$token = getWeChatToken($platform["appid"],$platform["secret"]);
			}			
			//D("test")->add(array("test"=>$token));
			$res = $this->sendImgAll($token,$datanews, $object->FromUserName);
			/*$resjson = json_decode($res,true);
			if ($resjson['errcode'] == 0) {
					//echo "推送完成";die;
					D("test")->add(array("test"=>"推送完成"));
			}else{
					//echo "推送失败";die;
					D("test")->add(array("test"=>"推送失败"));
			}			*/
			//$content = $object->FromUserName;
			$content = "";
		}
		
		
		if(is_array($content)){
			if (isset($content[0])){
				$result = $this->transmitNews($object, $content);
			}else if (isset($content['MusicUrl'])){
				$result = $this->transmitMusic($object, $content);
			}
		}else{
			$result = $this->transmitText($object, $content);
		}
		return $result;
	}
	
	/**
	 * 群发图文接口(多图文推送) 
	 * */
	protected function sendImgAll($token,$datanews,$open_id)
	{		
		$lasturl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$token";
		$data = '{
				    "touser":"'.$open_id.'",
				    "msgtype":"news",
				    "news":'.$datanews.'
				}
		';		
		return $result = weChatCurl($lasturl, 1, $data);
	}	
	
	//接收图片消息
	private function receiveImage($object)
	{
		$content = array("MediaId"=>$object->MediaId);
		$result = $this->transmitImage($object, $content);
		return $result;
	}
	
	//接收位置消息
	private function receiveLocation($object)
	{
		$content = "你发送的是位置，经度为：".$object->Location_Y."；纬度为：".$object->Location_X."；缩放级别为：".$object->Scale."；位置为：".$object->Label;
		$result = $this->transmitText($object, $content);
		return $result;
	}
	
	//接收语音消息
	private function receiveVoice($object)
	{
		if (isset($object->Recognition) && !empty($object->Recognition)){
			$content = "你刚才说的是：".$object->Recognition;
			$result = $this->transmitText($object, $content);
		}else{
			$content = array("MediaId"=>$object->MediaId);
			$result = $this->transmitVoice($object, $content);
		}
		return $result;
	}
	
	//接收视频消息
	private function receiveVideo($object)
	{
		$content = array("MediaId"=>$object->MediaId, "ThumbMediaId"=>$object->ThumbMediaId, "Title"=>"", "Description"=>"");
		$result = $this->transmitVideo($object, $content);
		return $result;
	}
	
	//接收链接消息
	private function receiveLink($object)
	{
		$content = "你发送的是链接，标题为：".$object->Title."；内容为：".$object->Description."；链接地址为：".$object->Url;
		$result = $this->transmitText($object, $content);
		return $result;
	}
	
	//回复文本消息
	private function transmitText($object, $content)
	{
		if (!isset($content) || empty($content)){
			return "";
		}
		
		$xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[%s]]></Content>
</xml>";
		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
		
		return $result;
	}
	
	//回复图文消息
	private function transmitNews($object, $newsArray)
	{
		if(!is_array($newsArray)){
			return "";
		}
		$itemTpl = "        <item>
            <Title><![CDATA[%s]]></Title>
            <Description><![CDATA[%s]]></Description>
            <PicUrl><![CDATA[%s]]></PicUrl>
            <Url><![CDATA[%s]]></Url>
        </item>
";
		$item_str = "";
		foreach ($newsArray as $item){
			$item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
		}
		$xmlTpl = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[news]]></MsgType>
		<ArticleCount>%s</ArticleCount>
		<Articles>
		$item_str    </Articles>
		</xml>";
		
		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
		return $result;
	}
	
	//回复音乐消息
	private function transmitMusic($object, $musicArray)
	{
		if(!is_array($musicArray)){
			return "";
		}
		$itemTpl = "<Music>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <MusicUrl><![CDATA[%s]]></MusicUrl>
        <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
    </Music>";
		
		$item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);
		
		$xmlTpl = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[music]]></MsgType>
		$item_str
		</xml>";
		
		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
		return $result;
	}
	
	//回复图片消息
	private function transmitImage($object, $imageArray)
	{
		$itemTpl = "<Image>
        <MediaId><![CDATA[%s]]></MediaId>
    </Image>";
		
		$item_str = sprintf($itemTpl, $imageArray['MediaId']);
		
		$xmlTpl = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[image]]></MsgType>
		$item_str
		</xml>";
		
		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
		return $result;
	}
	
	//回复语音消息
	private function transmitVoice($object, $voiceArray)
	{
		$itemTpl = "<Voice>
        <MediaId><![CDATA[%s]]></MediaId>
    </Voice>";
		
		$item_str = sprintf($itemTpl, $voiceArray['MediaId']);
		$xmlTpl = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[voice]]></MsgType>
		$item_str
		</xml>";
		
		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
		return $result;
	}
	
	//回复视频消息
	private function transmitVideo($object, $videoArray)
	{
		$itemTpl = "<Video>
        <MediaId><![CDATA[%s]]></MediaId>
        <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
    </Video>";
		
		$item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);
		
		$xmlTpl = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[video]]></MsgType>
		$item_str
		</xml>";
		
		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
		return $result;
	}
	
	//日志记录
	private function logger($log_content)
	{
		if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
			sae_set_display_errors(false);
			sae_debug($log_content);
			sae_set_display_errors(true);
		}else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
			$max_size = 1000000;
			$log_filename = "log.xml";
			if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
			file_put_contents($log_filename, date('Y-m-d H:i:s')." ".$log_content."\r\n", FILE_APPEND);
		}
	}

	/**
	 * 推送模板信息
	 * */
	protected function sendtemplateinfo($domain, $title,$old_nickname, $money,$open_id){		
				
		$map["domain"] = $domain;
		$platform = D("platform")->where($map)->find();
		if(intval($platform["out_time"]) > time())	{
			$token = getWeChatToken($platform["appid"],$platform["secret"],$platform["token"]);
		}
		else{
			$token = getWeChatToken($platform["appid"],$platform["secret"]);
		}
		//$token = "uE8o4BowpwHdc732mj869AkKGtrVB0Dumi1Hyu_ifLeSVNILA9Yyt1ZfXKJ8P3FpqPk7zYTEKUwD29O4gTAcoVs_NlY070ytewXeqran8iXXGeMLuzug58Sn3X9H2qVJHWXaACAVKL";
		//$openid = "ols0swsTiYZAdF6cdXxvTJqOWWCk"; 
		
		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$token";
		$data = '{
		           "touser":"'.$open_id.'",
		           "template_id":"7GuUjs3yajSmzNk5b7GssMq7oT7gKeKIOpSoZ73NR8w",
		         
		           "data":{
	                   "first": {
	                       "value":"'.$title.'",
	                       "color":"#173177"
	                   },
	                   "keyword1":{
	                       "value":"推荐关注送书币活动",
	                       "color":"#173177"
	                   },
	                   "keyword2": {
	                       "value":"'.$old_nickname.'",
	                       "color":"#173177"
	                   },
					   "keyword3": {
	                       "value":"'.$money.'书币",
	                       "color":"#173177"
	                   },
	                   "remark":{
	                       "value":"感谢您对本活动的大力支持",
	                       "color":"#173177"
	                   }
		           }
				}';
		$result = weChatCurl($url, 1, $data);
		foreach($result as $k=>$v){
			$test['test'] = $k.'-----'.$v;
					D('test')->add($test);
		}
		//print_r($result);
	}
}